﻿using Entity.Models;
using HuaRunInterface.Comm;
using HuaRunInterface.Models;
using Microsoft.AspNetCore.Mvc;
using Utility;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HuaRunInterface.Controllers.DeleteControllers
{
    [Route("api/HuaRun/[controller]")]
    [ApiController]
    public class DeleteRTUInfoController : ControllerBase
    {
        // POST api/<DeleteRTUInfoController>
        [HttpPost]
        public object Post([FromBody] RTUInfo value)
        {
            return DeleteData(value);
        }

        private object DeleteData(RTUInfo dto)
        {
            ReturnData rd = new ReturnData();

            try
            {
                string conn = Global.Configuration["ConnectionStrings:DDb"];

                using (Entity.DBContext context = Entity.BaseContext.CreateContext(conn))
                {
                    RTUInfo v = context.rTUInfos.Where(p => p.ID == dto.ID).FirstOrDefault();
                    if (v == null)
                    {
                        throw new Exception("表具信息没有找到！");
                    }
                    v.IsDelete = 1;
                    v.DeleteDate = DateTime.Now;
                    v.ResultMsg = "前端调用删除";
                    context.rTUInfos.Update(v);
                    string msg = "";
                    if (!string.IsNullOrWhiteSpace(v.uniqueDeviceIdentifier))
                    {
                        RTUDeleteModel model = v.SerializerObjectToString().JSONStringToObject<RTUDeleteModel>();
                        bool mr = Global.RTUDelete(model, ref msg);
                        if (mr)
                        {
                            int c = context.SaveChanges();
                        }
                        rd.State = mr ? "success" : "failed";
                        rd.Message = msg;
                    }
                    else
                    {
                        int c = context.SaveChanges();
                        rd.State = c > 0 ? "success" : "failed";
                        rd.Message = msg;
                    }
                }
            }
            catch (Exception ex)
            {
                rd.State = "failed";
                rd.Message = ex.Message;
                rd.Data = ex.StackTrace;
            }
            return rd;
        }
    }
}
